<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="btnController">
        <el-button v-if="false" class="buttons" @click=";(dialogFormVisible = true), (dialogStatus = 'create')">
          添加
        </el-button>
      </div>
      <div class="formContainer">
        <label class="filterLabel">关键词 :</label>
        <el-input v-model="listQuery.keyword" clearable placeholder="请输入" class="filterInput" @keyup.enter.native="handleFilter" />
        <el-button class="buttons" icon="el-icon-search" @click="handleFilter">
          搜索
        </el-button>
        <el-select v-model="excelType" style="margin-left: 20px;" placeholder="导出Excel" :loading="downloadLoading" @change="handleExpload">
          <el-option label="当前页面" :value="1" />
          <el-option label="所有页面" :value="2" />
        </el-select>
      </div>
    </div>
    <el-table :key="tableKey" :header-cell-style="{ background: '#ebebeb', height: '#54px' }" :data="list" style="width: 100%;" @sort-change="sortChange">
      <el-table-column label="序号" type="index" sortable="custom" align="center" width="80" :class-name="getSortClass('id')" />
      <!-- <el-table-column label="用户名" align="center">
        <template slot-scope="{ row }">
          {{ row.username }}
        </template>
      </el-table-column> -->

      <el-table-column label="姓名" align="center">
        <template slot-scope="{ row }">
          {{ row.realname }}
        </template>
      </el-table-column>
      <el-table-column label="手机" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.mobile }}</span>
        </template>
      </el-table-column>
      <el-table-column label="昵称" align="center">
        <template slot-scope="{ row }">
          {{ row.nickname }}
        </template>
      </el-table-column>
      <el-table-column label="微信ID" align="center">
        <template slot-scope="{ row }">
          {{ row.wxopenid }}
        </template>
      </el-table-column>
      <el-table-column label="上级信息" align="center" width="330">
        <template slot-scope="{ row }">
          <div v-if="row.parentData.wxopenid">
            微信ID: {{ row.parentData.wxopenid }}</br>
            电话：{{ row.parentData.mobile }}
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="渠道" align="center" width="330">
        <template slot-scope="{ row }">
          <div v-if="row.scenicData&&row.scenicData!=='[]'">
            <span>{{ row.scenicData.name }}</span>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>

      <el-table-column label="卡号" align="center">
        <template slot-scope="{ row }">
          {{ row.code }}
        </template>
      </el-table-column>
      <el-table-column label="卡号状态" align="center">
        <template slot-scope="{ row }">
          {{ row.code_status_name }}
        </template>
      </el-table-column>
      <el-table-column label="卡号积分" prop="score" sortable="custom" align="center">
        <template slot-scope="{ row }">
          {{ row.score }}
        </template>
      </el-table-column>
      <el-table-column label="等级" prop="level_name" sortable="custom" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.level_name }}</span>
        </template>
      </el-table-column>

      <el-table-column label="注册时间" prop="addtime" sortable="custom" align="center">
        <template slot-scope="{ row }">
          {{ row.addtime }}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="{ row }">
          <span :class="row.status === 1 ? 'main-success' : 'main-error'" @click="lineSearch('isverify', parseInt(row.status))">{{ row.status_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width">
        <template slot-scope="{ row, $index }">
          <el-popconfirm v-if="row.status===1" confirm-button-text="好的" cancel-button-text="不用了" icon="el-icon-info" icon-color="red" title="您确定要冻结该账号么？" @onConfirm="handleOpreat(row, $index)">
            <el-button slot="reference" size="mini" type="danger" plain>冻结</el-button>
          </el-popconfirm>
          <el-popconfirm v-else confirm-button-text="好的" cancel-button-text="不用了" icon="el-icon-info" icon-color="red" title="您确定要启用？" @onConfirm="handleOpreat(row, $index)">
            <el-button slot="reference" size="mini" type="primary" plain>启用</el-button>
          </el-popconfirm>
          <el-popconfirm v-if="false" confirm-button-text="好的" cancel-button-text="不用了" icon="el-icon-info" icon-color="red" title="删除后不可以恢复，确定删除吗？" @onConfirm="handleDelete(row, $index)">
            <el-button slot="reference" size="mini" type="danger">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.per_page" @pagination="getList" />
    <!-- 编辑、 添加弹框表单 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form ref="dataForm" :rules="rules" :model="rows" label-position="right" label-width="90px" style="width: 400px; margin-left:50px;">
        <el-form-item label="昵称" prop="nickname" class="marginTop30">
          <el-input v-model="rows.nickname" placeholder="请填写企业名称" />
        </el-form-item>
        <el-form-item label="企业类型" prop="member_type" class="marginTop30">
          <el-select v-model="rows.member_type" style="width: 260px;" clearable placeholder="请选择">
            <el-option v-for="(types, index) in enterpriseTypes" :key="index" :label="types" :value="index">{{ types }}</el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="用户名" prop="username">
          <el-input v-model="rows.username" autocomplete="new-password" placeholder="请填写用户名" />
        </el-form-item> -->
        <el-form-item label="手机号码" prop="mobile" class="marginTop30">
          <el-input v-model="rows.mobile" maxlength="11" autocomplete="new-password" placeholder="请填写手机号码" />
        </el-form-item>
        <div>
          <el-form-item label="密码" class="marginTop30" prop="password">
            <el-input v-model="rows.password" type="password" autocomplete="new-password" placeholder="请填写密码" />
          </el-form-item>
          <el-form-item label="确认密码" class="marginTop30" autocomplete="new-password" prop="passwordA">
            <el-input v-model="rows.passwordA" type="password" placeholder="请再次填写密码" />
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>
    <!--  -->
    <el-dialog :visible.sync="dialogPvVisible" title="编辑用户">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">提交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { search, add, edit, del, rows, editUser } from '@/api/user'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { notifySuccess, notifyError } from '@/utils/message'
import { getIP, parseTime } from '@/utils/index'
export default {
  name: 'UsersIndex',
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        normal: '正常',
        hidden: '隐藏'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      excelType: null,
      enterpriseTypes: null,
      expandAll: false,
      checkedKeys: [],
      tableKey: 0,
      list: null,
      total: 0,
      listQuery: {
        page: 1,
        per_page: 15,
        keyword: '',
        keywordb: '',
        type: null,
        isverify: null,
        sort: '',
        addtimestart: 0,
        addtimeend: 0,
        mobile: null,
        tel: null
      },
      dataRange: [],
      importanceOptions: [1, 2, 3],
      sortOptions: [
        { label: 'ID Ascending', key: '+id' },
        { label: 'ID Descending', key: '-id' }
      ],
      statusOptions: { normal: '正常', hidden: '隐藏' },
      showReviewer: false,
      rows: {
        id: '',
        member_type: null,
        mobile: '',
        username: '',
        enterprise_name: '',
        password: '',
        passwordA: '',
        ip: '',
        agent: 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '更新',
        create: '添加'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        member_type: [{ required: true, message: '企业类型', trigger: 'change' }],
        mobile: [{ required: true, message: '不能为空', trigger: 'blur' }],
        name: [{ required: true, message: '不能为空', trigger: 'blur' }],
        username: [{ required: true, message: '不能为空', trigger: 'blur' }],
        enterprise_name: [{ required: true, message: '不能为空', trigger: 'blur' }],
        password: [{ required: true, message: '不能为空', trigger: 'blur' }],
        passwordA: [{ required: true, message: '不能为空', trigger: 'blur' }]
      },
      downloadLoading: false,
      groupOption: {},
      handleInfos: {}
    }
  },
  created() {
    if (this.$route.params.keyword || this.$route.query.keyword) {
      this.listQuery.keyword = this.$route.params.keyword ? this.$route.params.keyword : this.$route.query.keyword
    }
    this.getList()
    // this.handleInfo()
  },
  methods: {
    // 获取列表数据
    getList() {
      var that = this
      this.listLoading = true
      const kw = this.listQuery.keyword
      this.listQuery.keyword = kw.trim()
      search(this.listQuery).then((response) => {
        this.list = response.data.data
        this.total = response.data.total
        // Just to simulate the time of the request
        setTimeout(() => {
          that.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      console.log(data)
      const { prop, order } = data
      const sorts = order === 'ascending' ? '_a' : '_d'
      this.listQuery.sort = prop + sorts
      // this.sortByID(order)
      this.handleFilter()
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetRows() {
      this.rows = {
        member_type: null,
        mobile: '',
        username: '',
        enterprise_name: '',
        password: '',
        passwordA: '',
        ip: '',
        agent: ''
      }
    },
    handleCreate() {
      this.resetRows()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    openIng() {
      notifyError('开发中')
    },
    // 新增提交方法
    async createData() {
      const that = this
      const ipaddres = await getIP()
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          add(that.rows.mobile, that.rows.username, that.rows.enterprise_name, that.rows.password, that.rows.passwordA, ipaddres, that.rows.agent, that.rows.member_type).then((response) => {
            // that.list.unshift(this.temp)
            that.dialogFormVisible = false
            notifySuccess('新增成功')
            that.getList()
          })
        }
      })
    },
    // 编辑数据
    handleUpdate(row) {
      const that = this
      this.roledata.id = row.id
      rows(row.id).then(function(res) {
        that.rows = Object.assign({}, res.data) // copy obj
        that.rows.ids = row.id
      })
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleOpreat(rows) {
      editUser({ id: rows.id, status: rows.status === 1 ? 2 : 1 }).then((res) => {
        this.getList()
        notifySuccess(res.msg || '编辑成功')
      })
    },
    updateData() {
      const that = this
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.rows)
          edit(tempData.id, tempData.pid, tempData.name, tempData.status, tempData.rules).then((res) => {
            const index = that.list.findIndex((v) => v.id === that.rows.ids)
            that.list.splice(index, 1, that.rows)
            that.dialogFormVisible = false
            notifySuccess(res.msg || '编辑成功')
          })
        }
      })
    },
    // 删除操作
    handleDelete(row, index) {
      // var that = this
      del(row.id).then((res) => {
        notifySuccess(res.msg || '删除成功')
        this.getList()
        // that.list.splice(index, 1)
      })
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    // 处理前数据
    // handleInfo() {
    //   handleBefore().then((res) => {
    //     this.handleInfos = res.data
    //     this.enterpriseTypes = res.data.enterprise_member_type
    //   })
    // },
    // 行内搜索
    lineSearch(column, val) {
      this.listQuery[column] = val
      this.getList()
    },
    // 导出EXCEL
    async handleExpload() {
      console.log(this.excelType)
      this.downloadLoading = true
      const that = this
      let templateList = Object.assign(that.list)
      const loading = this.$loading({
        lock: true,
        text: '加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      if (this.excelType === 2) {
        const tempQuery = Object.assign(that.listQuery)
        tempQuery.page = 1
        tempQuery.per_page = this.total
        await search(tempQuery).then((response) => {
          templateList = response.data.data
        })
      }
      loading.close()
      import('@/vendor/Export2Excel').then((excel) => {
        const tHeader = ['序号', '姓名', '手机', '昵称', '微信ID', '上级信息OPENID', '上级电话', '渠道', '卡号', '卡号状态', '卡号积分', '等级', '注册时间', '状态']
        const filterVal = ['id', 'realname', 'mobile', 'nickname', 'wxopenid', 'parentData', 'parentmobile', 'scenicData', 'code', 'code_status_name', 'score', 'level_name', 'addtime', 'status_name']
        const data = that.formatJson(filterVal, templateList)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) =>
        filterVal.map((j) => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else if (j === 'parentmobile') {
            return v['parentData']['mobile'] ? v['parentData']['mobile'] : '-'
          } else if (j === 'parentData') {
            return v['parentData']['wxopenid'] ? v['parentData']['wxopenid'] : '-'
          } else if (j === 'scenicData') {
            return v[j]['name']
          } else {
            return v[j]
          }
        })
      )
    }
  }
}
</script>
<style scoped >
.main-success {
  color: #409eff;
}
.main-error {
  color: #e6a23c;
}
/deep/ .el-select .el-input__inner {
  background-color: #66b1ff;
  color: #fff;
}
/deep/ .el-select .el-input__inner::placeholder {
  color: #fff;
}
</style>
